package com.heima.wemedia.interceptor;


import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.WmThreadLocalUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //得到header信息
        String token = request.getHeader("token");
        Optional<String> optional = Optional.ofNullable(token);
        if (optional.isPresent()) {
                //2.解析token,获取用户id
                Claims claimsBody = AppJwtUtil.getClaimsBody(token);
                if (claimsBody!=null) {
                Integer userId = (Integer) claimsBody.get("id");
                //3.存入threadLocal中
                WmUser wmUser = new WmUser();
                wmUser.setId(userId);
                WmThreadLocalUtil.setUser(wmUser);
            }

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("清理threadlocal...");
        WmThreadLocalUtil.clear();
    }
}
